package day02;
import javax.print.attribute.standard.JobName;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Timer;
import java.util.TimerTask;

public class Y {
    public static void main(String[] args) {
        JFrame frame = new JFrame("羊了个羊");
        JPanel panel = new JPanel(null);//消除布局
        JLabel background = new JLabel(new ImageIcon("images/背景.jpg"));
        frame.setIconImage(new ImageIcon("images/草.png").getImage());
        background.setSize(480,800);
        panel.add(background);
        frame.add(panel);
        frame.setSize(492,842);
        frame.setLocationRelativeTo(null);//窗口居中
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭窗口，关闭程序
        initGame(panel);
        frame.setVisible(true);
    }

    private static void initGame(JPanel panel) {
        ArrayList<JButton> cards = creatCards(9);
        ArrayList<JButton> trough = new ArrayList<>();//trough 槽子
        Collections.shuffle(cards);//洗牌
        poseForCards(panel, cards,7,7,0,30,100);
        poseForCards(panel, cards,6,6,49,60,130);
        poseForCards(panel, cards,5,7,49+36,30,160);
        poseForCards(panel, cards,6,6,49+36+35,60,130+60);
        checkCovered(cards);
        addAction(cards, trough, panel);//点击事件
    }

    /**
     * 从槽子里删除成对的牌
     * @param trough   槽子
     * @param index   刚刚插入的卡牌位置
     * @param current 刚刚插入的卡牌
     * @param panel 面板
     */
    static Timer timer = new Timer();
    public static void removePairedCards(ArrayList<JButton> trough, int index, JButton current,
                                         JPanel panel, ArrayList<JButton> cards) {
        if (trough.size() - index < 3) {
            return;
        }//检查当前位置开始到槽子的最后位置，如果不够三张牌，就不需要删除
        JButton nextNextCard = trough.get(index + 2);//获取当前位置的下下张牌
        if (current.getName().equals(nextNextCard.getName())) {//比较当前排和下下张牌的名字是否一样
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //如果一样就删除3张牌
                    JButton card = trough.remove(index);
                    panel.remove(card);
                    card = trough.remove(index);
                    panel.remove(card);
                    card = trough.remove(index);
                    panel.remove(card);
                    updateTroughCardsLocation(trough, panel);
                    if (cards.isEmpty()) {
                        JOptionPane.showMessageDialog(panel, "YOU WIN!");


                    }

                }
            },200);
        }
    }
    public static void updateTroughCardsLocation(ArrayList<JButton> trough, JPanel panel){
        for (int i = 0; i <trough.size() ; i++) {
            JButton card = trough.get(i);
            card.setLocation(20+i*63,642);
        }
        panel.updateUI();//触发界面更新，去除界面残留的卡牌影子
    }
    private static void addAction(ArrayList<JButton> cards, ArrayList<JButton> trough,
                                  JPanel panel) {
        for (int i = 0; i < cards.size(); i++) {
            JButton card = cards.get(i);
            card.addActionListener(e -> {
                // e称为事件  其中包含点击时候发生的数据，鼠标位置，点击时间
                // 被点击的当前对象，e.getSource() 方法返回被点击的对象
                //Source来源，是发生时间时候的当前对象
                JButton current = (JButton) e.getSource();
                System.out.println(current.getName());
                if (trough.size() == 7) {
                    //show  显示   Message  消息    dialog对话框
                    JOptionPane.showMessageDialog(panel,"YOU LOSE！");
                    return;
                }
                    addCardToTrough(panel,cards, trough, current);
            });

        }
    }
    /**
     * 将当前被点击的牌添加到槽子
     * @param cards    牌
     * @param trough  槽子
     * @param current  当前的
     */

    private static void addCardToTrough(JPanel panel, ArrayList<JButton> cards, ArrayList<JButton> trough,
                                        JButton current) {
        cards.remove(current);//从上面一堆牌中删除被点击的牌
        //删除牌上的鼠标事件
        current.removeActionListener(current.getActionListeners()[0]);
        checkCovered(cards);
        int index = 0;//插入位置
        for (; index <trough.size() ; index++) {
            JButton card = trough.get(index);
            if (card.getName().equals(current.getName())) {
                break;
            }
        }
        trough.add(index, current);//插入当前位置
        removePairedCards(trough, index, current, panel, cards);//删除槽子中配对的牌
        for (int i = 0; i <trough.size() ; i++) {
            JButton card = trough.get(i);
            card.setLocation(20+i*63,642);
        }
        panel.updateUI();
    }

    /**
     * 检查卡牌的遮挡关系
     * 检查每个牌  如果这个牌被后续牌遮挡  这个牌就设置为disable状态
     * @param cards  被检查的全部牌
     */
    public static void checkCovered(ArrayList<JButton> cards){
        for (int i=0; i<cards.size(); i++){
            //前面牌是下层牌c1
            JButton c1 = cards.get(i);
            c1.setEnabled(true);
            for (int j=i+1; j<cards.size(); j++){
                //c2代表c1后面的每个牌
                JButton c2 = cards.get(j);
                if(covered(c1, c2)){
                    //如果c1被压住, 则c1设置为disable, 不用再检查后续是否压住
                    c1.setEnabled(false);
                    break;
                }
            }
        }
    }


    /**
     *
     *检查c2是否压住了c1
     * c1是下方的卡牌
     * c2是上方卡牌
     *  return true表示压住了   false表示没压住
     */
    public static boolean covered(JButton c1,JButton c2){
        int x1 =c1.getX() - 59;
        int x2 =c1.getX() + 59;
        int y1 =c1.getY() - 59;
        int y2 =c1.getY() + 59;
        return (c2.getX()>x1 && c2.getX()<x2) && (c2.getY()>y1 && c2.getY()<y2);
    }

    private static void poseForCards(JPanel panel,
                                     ArrayList<JButton> cards,
                                     int rows,
                                     int cols,
                                     int offset,
                                     int x,int y) {//offset偏移    x,y摆放位置的起始点
        for (int i = 0; i < rows * cols; i++) {
            if (i+offset == cards.size()) {
                break;//打断循环
            }
            JButton card = cards.get(i+offset);//摆牌
            card.setLocation(x+59*(i%cols), y+i/cols*59);
            panel.add(card,0);
        }
    }

    private static ArrayList<JButton> creatCards(int rounds) {
        String[] names = {"刷子","剪刀","叉子","奶瓶","干草","手套","树桩","棉花","毛线","水桶",
                "火","玉米","白菜","草","萝卜","铃铛"};
        ArrayList<JButton> cards = new ArrayList<>();
        for (int j= 0; j <rounds ; j++) {
            for (int i = 0; i < names.length; i++) {
                String name = names[i];//数组中每个元素
                String filename = "images/" + name + ".png";
                String filename2 = "images/" + name + "2.png";
                JButton card = new JButton(new ImageIcon(filename));
                card.setDisabledIcon(new ImageIcon(filename2));
                card.setName(name);
                card.setSize(59, 66);
                card.setBorderPainted(false);//边框绘制不生效    Border 边界
                card.setContentAreaFilled(false);//内容不填充   Content 内容  Area区域  Filled 填充
                cards.add(card);
            }
        }
        return cards;
    }


}

